<template>
    <div class="max-w-4xl mx-auto py-8">
        <h1 class="text-3xl font-bold mb-8">
            {{ currentTagName ? `标签: ${currentTagName}` : '全部文章' }}
        </h1>
        <div class="px-4">
            <!-- 骨架屏 -->
            <template v-if="loading && posts.length === 0">
                <div v-for="i in 6" :key="i"
                    class="mb-0 px-2 py-6 border-b border-gray-200 last:border-b-0 animate-pulse">
                    <div class="h-6 w-1/3 bg-gray-200 rounded mb-4"></div>
                    <div class="h-4 w-4/5 bg-gray-200 rounded mb-2"></div>
                    <div class="h-4 w-1/2 bg-gray-200 rounded mb-2"></div>
                    <div class="flex space-x-4 mt-4">
                        <div class="h-4 w-12 bg-gray-200 rounded"></div>
                        <div class="h-4 w-12 bg-gray-200 rounded"></div>
                        <div class="h-4 w-12 bg-gray-200 rounded"></div>
                    </div>
                </div>
            </template>
            <!-- 文章列表 -->
            <template v-else>
                <div v-for="post in posts" :key="post.articleId"
                    class="mb-0 px-2 py-6 border-b border-gray-200 last:border-b-0 cursor-pointer transition duration-200"
                    @click="goDetail(post.articleId)" @mouseenter="hovered = post.articleId" @mouseleave="hovered = null"
                    :style="hovered === post.articleId ? { background: 'var(--post-hover-bg)', transform: 'scale(1.03)', borderBottomColor: 'var(--post-divider)' } : { borderBottomColor: 'var(--post-divider)' }">
                    <div class="flex items-center mb-2 space-x-2">
                        <span class="text-lg font-semibold">{{ post.title }}</span>
                    </div>
                    <div class="text-gray-500 text-sm mb-2 line-clamp-3 ">
                        {{ post.summary }}
                    </div>
                    <div class="flex items-center text-sm space-x-4 flex-wrap">
                        <span class="flex items-center gap-1">
                            <Icon icon="mdi:clock-outline" class="w-4 h-4" />
                            {{ formatPostTime(post.updatedAt) }}
                        </span>
                        <span class="flex items-center gap-1">
                            <Icon icon="mdi:eye-outline" class="w-4 h-4" />
                            {{ post.viewCount }}
                        </span>
                        <span class="flex items-center gap-1">
                            <Icon icon="mdi:thumb-up-outline" class="w-4 h-4" />
                            {{ post.likeCount }}
                        </span>
                        <span v-if="post.tags" class="flex flex-wrap gap-2 ml-2">
                            <span v-for="tag in post.tags.split(',')" :key="tag"
                                class="flex items-center gap-1 mr-2 tag-underline-animate">
                                <Icon icon="mdi:tag-outline" class="w-4 h-4" />
                                {{ tag }}
                            </span>
                        </span>
                    </div>
                </div>
                <!-- 加载中动画 -->
                <div v-if="loading && posts.length > 0" class="flex justify-center py-4">
                    <svg class="animate-spin h-6 w-6 text-emerald-500" xmlns="http://www.w3.org/2000/svg" fill="none"
                        viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4">
                        </circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z"></path>
                    </svg>
                    <span class="ml-2 text-gray-400">加载中...</span>
                </div>
                <!-- 没有更多 -->
                <div v-if="!hasMore && !loading" class="text-center text-gray-400 py-4">没有更多了</div>
            </template>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Icon } from '@iconify/vue'
import { formatPostTime } from '@/utils/timeFormat'
import { getArticleList, getArticlesByTagId } from '@/api/article'
import type { ArticleVO } from '@/types/article'

const posts = ref<ArticleVO[]>([])
const page = ref(1)
const pageSize = 10
const loading = ref(false)
const hasMore = ref(true)
const router = useRouter()
const route = useRoute()
const hovered = ref<number | null>(null)
const currentTagId = ref<number | null>(null)
const currentTagName = ref<string>('')


// 获取文章列表（真实接口）
async function fetchPosts() {
  loading.value = true
  try {
    let res
    if (currentTagId.value) {
      // 根据标签ID查询文章
      res = await getArticlesByTagId(currentTagId.value, { page: page.value, size: pageSize })
    } else {
      // 获取所有文章
      res = await getArticleList({ page: page.value, size: pageSize })
    }
    
    if (res.data) {
      posts.value.push(...res.data)
      hasMore.value = res.data.length === pageSize
    } else {
      hasMore.value = false
    }
  } finally {
    loading.value = false
  }
}

function goDetail(id: number) {
  router.push(`/posts/${id}`)
}

// 重置文章列表
function resetPosts() {
  posts.value = []
  page.value = 1
  hasMore.value = true
}

// 监听路由参数变化
watch(() => route.query, (newQuery) => {
  const tagId = newQuery.tagId ? parseInt(newQuery.tagId as string) : null
  const tagName = newQuery.tagName as string
  
  if (tagId !== currentTagId.value) {
    currentTagId.value = tagId
    currentTagName.value = tagName || ''
    resetPosts()
    fetchPosts()
  }
})

// 触底加载
function onScroll() {
  if (!hasMore.value || loading.value) return
  const scrollTop = window.scrollY || document.documentElement.scrollTop
  const clientHeight = window.innerHeight || document.documentElement.clientHeight
  const scrollHeight = document.documentElement.scrollHeight
  if (scrollTop + clientHeight >= scrollHeight - 100) {
    page.value++
    fetchPosts()
  }
}

onMounted(() => {
  // 初始化时从路由参数获取标签信息
  const tagId = route.query.tagId ? parseInt(route.query.tagId as string) : null
  const tagName = route.query.tagName as string
  
  currentTagId.value = tagId
  currentTagName.value = tagName || ''
  
  fetchPosts()
  window.addEventListener('scroll', onScroll)
})

onUnmounted(() => {
  window.removeEventListener('scroll', onScroll)
})
</script>

<style>
:root {
    --post-hover-bg: #f0fdf4;
    --post-divider: #e5e7eb;
}

.dark {
    --post-hover-bg: #23272e;
    --post-divider: #33363b;
}
</style>